//
//  DYBLEManager.m
//  DYPrintSDK
//
//  Created by mr.ye on 2023/11/20.
//

#import "DYBLEManager.h"


@interface DYBLEManager ()<CBCentralManagerDelegate, CBPeripheralDelegate>
//蓝牙管理类
@property (nonatomic , strong) CBCentralManager *manager;
//队列
@property (nonatomic , strong) dispatch_queue_t queue;

//蓝牙状态
@property (nonatomic , assign) CBManagerState bleState;

@property (nonatomic , strong, nullable) CBPeripheral *peripheral;

//搜索回调block
@property (nonatomic , copy)DYBLEManagerCall searchCompletion;

//连接状态
@property (nonatomic , copy)DYBLEManagerConnetCall connetCompletion;

//定时记录连接的时候
@property (nonatomic , strong)NSTimer * connectTimer;

//连接时间
@property (nonatomic , assign)NSInteger connectTime;


@end

@implementation DYBLEManager

DYBLEManager *_shared = nil;

+ (DYBLEManager *)sharedInstance {
    static dispatch_once_t onceToken;
    dispatch_once(&onceToken, ^{
        _shared = [[DYBLEManager alloc] init];
    });
    return _shared;
}

- (instancetype)init {
    if (self = [super init]) {
        self.queue = dispatch_queue_create("com.luckjingle.sdk", DISPATCH_QUEUE_SERIAL);
        self.manager = [[CBCentralManager alloc] initWithDelegate:self queue:self.queue];
        self.print =[[DYPrinterManager alloc]init];
    }
    return self;
}

#pragma mark--------------事件------------------
#pragma mark --搜索蓝牙--
- (void)scanPrinters:(NSTimeInterval)interval call:(DYBLEManagerCall)completion err:(DYBLEManagerCall)errCall{
    
    dispatch_after(dispatch_time(DISPATCH_TIME_NOW, (int64_t)(0.5 * NSEC_PER_SEC)), dispatch_get_main_queue(), ^{
       
        if (self.bleState != CBManagerStatePoweredOn) {
            NSError *error = [NSError errorWithDomain:@"com.DYPrint.sdk"
                                                 code:1001
                                             userInfo:@{NSLocalizedDescriptionKey: @"蓝牙不可用，请检查蓝牙是否已开启"}];
            errCall(error);
            return;
        }
        
        [self stopScanPrinters];
      
        self.searchCompletion = completion;
        
        NSDictionary *option = @{CBCentralManagerScanOptionAllowDuplicatesKey : [NSNumber numberWithBool:NO],CBCentralManagerOptionShowPowerAlertKey:[NSNumber numberWithBool:YES]};
        [self.manager scanForPeripheralsWithServices:@[] options:option];
        
        //设定结束搜索事件
        if(interval>0){
            dispatch_after(dispatch_time(DISPATCH_TIME_NOW, (int64_t)(interval * NSEC_PER_SEC)), dispatch_get_main_queue(), ^{
                [self stopScanPrinters];
//                NSLog(@"定时结束搜索");
            });
        }
        
        
    });
    
    
    
}

#pragma mark --停止搜索--
-(void)stopScanPrinters {
    if ([self.manager isScanning]) {
        NSLog(@"stop scan");
        [self.manager stopScan];
    }
}

/// 连接设备
/// - Parameters:
///   - peripheral: 设备对象
///   - interval: 超时时间
- (void)connect:(CBPeripheral *)peripheral timeout:(NSTimeInterval)interval call:(DYBLEManagerConnetCall)completion{
    if (self.bleState != CBManagerStatePoweredOn) {
        return;
    }
    self.connetCompletion = completion;
    [self stopScanPrinters];
    NSLog(@"connecting printer [%@]",peripheral.name);
    [self.manager connectPeripheral:peripheral options:@{}];
    
    
    
    //指定内没连接成功，取消连接，判定失败
    self.connectTimer = [NSTimer timerWithTimeInterval:1 repeats:YES block:^(NSTimer * _Nonnull timer) {
        if(self.connectTime==interval){
            [self.connectTimer invalidate];
             self.connectTime = 0;
            NSError *error = [NSError errorWithDomain:@"com.DYPrint.sdk"
                                                               code:1001
                                                           userInfo:@{NSLocalizedDescriptionKey:@"连接超时,检查打印是否开机"}];
            completion(peripheral,error);
        }
        self.connectTime +=1;
        
    }];
    
    [[NSRunLoop currentRunLoop]addTimer:self.connectTimer forMode:NSRunLoopCommonModes];
    [self.connectTimer fire];
}


#pragma mark - 蓝牙CBCentralManagerDelegate代理
#pragma mark-蓝牙状态回调---
- (void)centralManagerDidUpdateState:(CBCentralManager *)central {
//    NSLog(@"蓝牙状态===== [%ld]", central.state);
    self.bleState = central.state;
    dispatch_async(dispatch_get_main_queue(), ^{
        [NSNotificationCenter.defaultCenter postNotificationName:BleDidChangeState object:@{@"state": @(central.state)}];
    });
    
}

#pragma mark-蓝牙搜索后回调---
- (void)centralManager:(CBCentralManager *)central didDiscoverPeripheral:(CBPeripheral *)peripheral advertisementData:(NSDictionary<NSString *, id> *)advertisementData RSSI:(NSNumber *)RSSI {
    NSString *name = advertisementData[@"kCBAdvDataLocalName"];
    
    //搜索回调回去
    if(self.searchCompletion){
        if(name.length<=0){return;}
        
        dispatch_async(dispatch_get_main_queue(), ^{
            self.searchCompletion(@{@"peripheral": peripheral, @"advertisementData":advertisementData, @"RSSI":RSSI});
        });
    }
    
}



#pragma mark-蓝牙连接成功---
- (void)centralManager:(CBCentralManager *)central didConnectPeripheral:(CBPeripheral *)peripheral {
//    NSLog(@"连接成功-----");
    self.peripheral = peripheral;
    [self.connectTimer invalidate];
     self.connectTime = 0;
    if(self.connetCompletion){
        dispatch_async(dispatch_get_main_queue(), ^{
            self.connetCompletion(peripheral, nil);
        });
        
        
    }
    
    NSUserDefaults *defaults = [NSUserDefaults standardUserDefaults];
    [defaults setObject:peripheral.identifier.UUIDString forKey:@"lastUUID"];
    
    self.print = [[DYPrinterManager alloc]initWithPeripheral:peripheral];
    [NSNotificationCenter.defaultCenter postNotificationName:BleDidConnectNotice object:@{@"peripheral":peripheral}];
    
}

- (void)centralManager:(CBCentralManager *)central didFailToConnectPeripheral:(CBPeripheral *)peripheral error:(nullable NSError *)error {
    if(self.connetCompletion){
        self.connetCompletion(peripheral, error);
    }
}
- (void)centralManager:(CBCentralManager *)central didDisconnectPeripheral:(CBPeripheral *)peripheral error:(nullable NSError *)error {
    [NSNotificationCenter.defaultCenter postNotificationName:BleDidDisconnectNotice object:@{@"peripheral":peripheral, @"error": error}];
}

/// 获取最后一次连接的UUID
-(NSString*)getLastConnectUUID{
    NSUserDefaults *defaults = [NSUserDefaults standardUserDefaults];
    return  [defaults valueForKey:@"lastUUID"];
}


@end
